import { ConverterBase } from './base';
import { Color, Label, LabelOutline, LabelShadow } from './cc';

export abstract class LabelConverterBase extends ConverterBase {
    protected abstract get typer(): any;

    public async convert() {
        const exportPSD = this.treePSD.export();
        const name = this.getName(exportPSD.name);
        const node = this.createNode({
            name: name.split('-')[1],
        });

        const text: any = exportPSD.text;
        const font: any = text.font;
        const lbl = this.appendComponent<Label>(this.typer, node);
        const colorCtor = ConverterBase.getCcPropFunc(Color.name);
        const rotation = Math.round(
            Math.atan2(text.transform.yx, text.transform.xx) * (180 / Math.PI) * 100
        ) / 100;
        const size = name.match(/fs(\d+)/)?.[1] as any ?? font.sizes[0];
        lbl.fontSize = +size;
        lbl.lineHeight = +size;
        lbl.color = new colorCtor(font.colors[0][0], font.colors[0][1], font.colors[0][2], font.colors[0][3]);
        lbl.horizontalAlign = 1; //美术默认左对齐无法修改.程序调整为默认居中
        lbl.verticalAlign = 1; //默认居中
        lbl.isBold = font.names.indexOf('Alibaba-PuHuiTi-B') != -1;
        lbl.isUnderline = font.textDecoration.indexOf('underline') != -1;
        lbl.isItalic = new Set(font.names).size !== font.names.length; // 有同样的字段表示斜体
        lbl.string = text.value.replace(/\r/g, '\n');
        node.setRotationFromEuler(ConverterBase.getCcPropFunc('v3')(0, 0, rotation));

        const regExp: any = name.indexOf('-o') !== -1 ? /o(.{6})/ : /s(.{6})/;
        const result = regExp.exec(name)?.[1];

        //描边
        if (name.indexOf('-o') !== -1) {
            const outLine = this.appendComponent<LabelOutline>(ConverterBase.getCcPropFunc('LabelOutline'), node);
            outLine.color = ConverterBase.getCcPropFunc('color')().fromHEX(result);
            //描边会位置出现偏移
            node.position = this.createVec3(this.x, this.y + 5);
        }

        //投影
        if (name.indexOf('-s') !== -1) {
            const shadow = this.appendComponent<LabelShadow>(ConverterBase.getCcPropFunc('LabelShadow'), node);
            shadow.color = ConverterBase.getCcPropFunc('color')().fromHEX(result);
            shadow.offset = ConverterBase.getCcPropFunc('v2')(0, -1);
        }
        
        return node;
    }

    protected abstract getName(layerName: string): string;
}